import React, { Component } from 'react';
import axios from './../../axios';
import zhCN from 'antd/es/locale/zh_CN';
import Utils from './../../utils/utils';
import { 
	Card,
	Table,
	Modal,
	Form,
	Input,
	Button,
	message,
	Tag,
	Pagination,
	ConfigProvider,
	Tree
} from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
const FormItem = Form.Item;

class RoleManage extends Component {
	
	searchFormRef = React.createRef();//搜索列表数据Form表单
	formRef = React.createRef();//创建与修改角色Form表单
	
	state={
		dataSource: [],//列表数据
		requestParams: {//请求列表数据的参数
			field: "", 
			value: "", 
			page: 1, 
			limit: 10
		},
		pageSizeOptions:["10","20","50"],//表格显示每页多少条分页记录数
		isVisible: false,//创建与修改角色模态框
		formTitle: "添加角色",//创建与修改角色模态框的标题
		selectedItem: {},//当前选中项
		apiTreeMenu: [],//api权限树
		treeMenu: [],//权限树
		apiMenuInfo: [],//api树控件选中项
		menuInfo: [],//树控件选中项
	}
	
	//获取列表数据
	requestList = (data) => {
		axios.ajax({
			url: "/Manager/RoleMng/roleRetrieve", 
			method: "post",
			data: data,
		}).then(res=>{
			if(res.code === 0){
				//Table的数据没有key就报错，自己加一个key
				let resData = res.result.data.map((item, index)=>{
					let key = index;
					return {...item, key}
				})
				this.setState({
					dataSource: resData,
					count: res.result.count
				})
			}
		}).catch(err=>{
		})
		
		//获取菜单
		axios.ajax({
			url: "/Manager/PermitMng/eleRetrieve", 
			method: "post",
			data: {
				field: "", 
				value: "", 
				page: 1, 
				limit: ""
			},
		}).then(res=>{
			if(res.code === 0){
				//Tree
				let resData = res.result.data.map((item, index)=>{
					let key = item.id;
					let title = item.name;
					return {title:title, key:key.toString()}
				})
				this.setState({
					treeMenu: resData
				})
			}
		}).catch(err=>{
		})
		
		//获取api
		axios.ajax({
			url: "/Manager/PermitMng/apiRetrieve", 
			method: "post",
			data: {
				field: "", 
				value: "", 
				page: 1, 
				limit: ""
			},
		}).then(res=>{
			if(res.code === 0){
				//Tree的数据格式
				let resData = res.result.data.map((item, index)=>{
					let key = item.id;
					let title = item.remark;
					return {title:title, key:key.toString()}
				})
				this.setState({
					apiTreeMenu: resData,
				})
			}
		}).catch(err=>{
		})
	}
	
	//分页功能，点击某页
	pageChange= (current, pageSize) => {
		let data = {...this.state.requestParams};
		data.page = current;
		data.limit = pageSize;
		this.setState({
			requestParams: data
		})
		this.requestList(data);
	}
	
	//分页功能，选择每页显示几个
	pageSizeChange = (current, pageSize) => {
		let data = {...this.state.requestParams};
		data.page = 1;
		data.limit = pageSize;
		this.setState({
			requestParams: data
		})
		this.requestList(data);
	}
	
	//查询角色信息
	searchSubmit = values => {
		let data = {...this.state.requestParams};
		if(!values.value){
			data.field = "";
			data.value = "";
		}else{
			data.field = "role_name";
			data.value = values.value;
		}
		this.setState({
			requestParams: data
		})
		this.requestList(data);
	}
	
	//api权限树选中的项保存起来
	onApiCheck = (checkedKeys) => {
		this.setState({
			apiMenuInfo: checkedKeys
		})
	}
	
	//权限树选中的项保存起来
	onCheck = (checkedKeys) => {
		this.setState({
			menuInfo: checkedKeys
		})
	}
	
	//点击创建角色
	createRole = () => {
		this.setState({isVisible: true, formTitle: "添加角色", apiMenuInfo: [], menuInfo: []});
		setTimeout(()=>{
			this.formRef.current.setFieldsValue({
				role_name: "",
				api_auth_ids: "",
				menu_ids: "",
				remark: ""
			});
			this.formRef.current.resetFields()
		},300)
	}
	
	//点击修改角色按钮
	roleUpdate = (record) => {
		this.setState({
			isVisible: true,
			selectedItem: record,
			formTitle: "修改角色"
		});
		setTimeout(()=>{
			this.formRef.current.setFieldsValue(record);
			this.setState({
				apiMenuInfo: record.api_auth_ids.split(","),
				menuInfo: record.menu_ids.split(",")
			})
		},300)
	}
	
	//创建与修改角色提交
	handleSubmit = () => {
		this.setState({isVisible: false});
		let data = this.formRef.current.getFieldsValue();
		function sortby(a,b){
			return a - b;
		}
		let apiTreeData = this.state.apiMenuInfo;
		
		let treeData = this.state.menuInfo;
		//删除all的那项
		let apiDeleteIndex = apiTreeData.indexOf("all");
		let deleteIndex = treeData.indexOf("all");
		if(apiDeleteIndex > -1){
			apiTreeData.splice(apiDeleteIndex,1);
		}
		if(deleteIndex > -1){
			treeData.splice(deleteIndex,1);
		}
		data.api_auth_ids = apiTreeData.sort(sortby).join(",");
		data.menu_ids = treeData.sort(sortby).join(",");
		let url = "";
		if(this.state.formTitle === "添加角色"){
			url = "/Manager/RoleMng/roleCreate";
		}else{
			url = "/Manager/RoleMng/roleUpdate";
			data.roleid = this.state.selectedItem.id;
		}
		axios.ajax({
			url: url,
			method: "post",
			data: data
		}).then(res=>{
			if(res.code === 0){
				message.success(res.msg);
				this.requestList(this.state.requestParams);
			}else{
				message.error(res.msg);
			}
		})
	}
	
	//删除角色
	roleDelete = record => {
		if(record.role_name === "超级管理员"){
			message.error(record.role_name + "不可删除");
		}else{
			Modal.confirm({
				title: `确认删除 ${record.role_name} ？`,
				icon: <ExclamationCircleOutlined />,
				content: "想好后再操作喔",
				okText: "确认删除",
				cancelText: "取消",
				onOk:()=>{
					axios.ajax({
						url: "/Manager/RoleMng/roleDelete",
						method: "post",
						data: {roleid: record.id}
					}).then(res=>{
						if(res.code === 0){
							message.success(res.msg);
							this.requestList(this.state.requestParams);
						}
					})
				}
			})
		}
	}
	
	//重置清空表单
	onReset = () => {
		this.formRef.current.resetFields();
		this.setState({
			menuInfo: []
		})
	}
	
	componentDidMount(){
		this.requestList(this.state.requestParams);
	}
	
	render(){
		const columns = [
			{
				title: '角色名',
				dataIndex: 'role_name',
				width: 150,
				fixed: 'left',
			},
			{
				title: '允许访问api',
				dataIndex: 'api_auth',
				render: items => {
					if(items.length < 1){
						return "";
					}else{
						return items.map(item => {
							return item.remark
						}).join("，")
					}
				}
			},
			{
				title: '显示的菜单',
				dataIndex: 'menu',
				render: items => {
					if(items.length < 1){
						return "";
					}else if(items.length === 10){
						return "全部";
					}else{
						return items.map(item => {
							return item.name
						}).join("，")
					}
				}
			},
			{
				title: '状态',
				dataIndex: 'is_del',
				width: 80,
				render: item => {
					return item === 1 ? <Tag color="red">已删除</Tag> : <Tag color="cyan">正常</Tag>;
				}
			},
			{
				title: '备注',
				dataIndex: 'remark',
				width: 150
			},
			{
				title: '创建时间',
				dataIndex: 'create_time',
				render: Utils.formateDate,
				width: 200
			},
			{
				title: '操作',
				key: 'action',
				fixed: 'right',
				width: 150,
				render: (text, record) => {
					return record.is_del?<Tag color="red">角色已删除</Tag>:
					record.role_name === "超级管理员"?
					<div>
						<Tag color="#108ee9" onClick={() => this.roleUpdate(record)}>编辑</Tag>
					</div>:
					<div>
						<Tag color="#108ee9" onClick={() => this.roleUpdate(record)}>编辑</Tag>
						<Tag color="#f45656" onClick={() => this.roleDelete(record)}>删除</Tag>
					</div>
				}
			}
		];
		const title = this.state.formTitle;
		const count = this.state.count;
		const current = this.state.requestParams.page;
		const pageSize = this.state.requestParams.limit;
		const apiMenuInfo = this.state.apiMenuInfo;
		const menuInfo = this.state.menuInfo;
		const layout = {
		    labelCol: { span: 6 },
		    wrapperCol: { span: 18 },
		};
		const tailLayout = {
		    wrapperCol: { offset: 6, span: 18 },
		};
		const apiTreeData = [{
			title: '全部',
			key: 'all',
			children: this.state.apiTreeMenu
		}]
		const treeData = [{
			title: '全部',
			key: 'all',
			children: this.state.treeMenu
		}]
		return (
			<div style={{padding: 20}}>
				<Card className="page-search-wrap">
					<Form layout="inline" ref={this.searchFormRef} onFinish={this.searchSubmit}>
						<FormItem
							label="角色名"
							name="value"
						>
						    <Input autoComplete="off" />
						</FormItem>
						<Form.Item>
							<Button type="primary" htmlType="submit">
							    查询
							</Button>
							<Button htmlType="button" onClick={()=>this.searchFormRef.current.resetFields()}>
								重置
							</Button>
						</Form.Item>
					</Form>
					<Button 
						type="primary"
						onClick={this.createRole}
						className="float-right"
					>
						创建角色
					</Button>
				</Card>
				<Card>
					<Table
						columns={columns}
						dataSource={this.state.dataSource}
						pagination={false}
						scroll={{x: 1300}}
					/>
					<ConfigProvider locale={zhCN}>
						<Pagination
							showQuickJumper
							showSizeChanger
							current={current}
							defaultPageSize={pageSize}
							total={count}
							showTotal={total => `共 ${total} 条`}
							pageSizeOptions={this.state.pageSizeOptions}
							onChange={this.pageChange}
							onShowSizeChange={this.pageSizeChange}
						/>
					</ConfigProvider>
				</Card>
				<Modal
					title={title}
					visible={this.state.isVisible}
					onCancel={()=>{this.setState({isVisible: false})}}
					footer={null}
				>
					<Form
						{...layout}
						ref={this.formRef}
						onFinish={this.handleSubmit}
					>
						<FormItem
							label="角色名"
							name="role_name"
							validateTrigger="onChange"
							rules={[
								{required: true, message: "请输入角色名"},
								{max:30,message:'请输入正确的角色名'}
							]}
						>
						    <Input autoComplete="off" />
						</FormItem>
						<FormItem
							label="允许访问api"
						>
						    <Tree
						    	checkable
						    	defaultExpandAll
						    	checkedKeys={apiMenuInfo}
						    	treeData={apiTreeData}
						    	onCheck={(checkedKeys)=>{this.onApiCheck(checkedKeys)}}
						    />
						</FormItem>
						<FormItem
							label="权限设置"
						>
							<Tree
								checkable
								defaultExpandAll
								checkedKeys={menuInfo}
								treeData={treeData}
								onCheck={(checkedKeys)=>{this.onCheck(checkedKeys)}}
							/>
						</FormItem>
						<FormItem
							label="备注"
							name="remark"
						>
						    <Input autoComplete="off" />
						</FormItem>
						<FormItem {...tailLayout}>
							<Button type="primary" htmlType="submit">
							    保存
							</Button>
							<Button htmlType="button" onClick={this.onReset}>
								重置
							</Button>
						</FormItem>
					</Form>
				</Modal>
			</div>
		)
	}
}

export default RoleManage;